package bean;


import java.util.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import controller.UserMgr;
import dto.UtenteDTO;

@ManagedBean(name="registerBean")
@ViewScoped
public class RegisterBean {
	
	@ManagedProperty(value="#{param.userb")
    String userb;
	@Resource(lookup = "EMailME")
	private Session mailSession;

	@EJB
	private UserMgr userMgr;

	private UtenteDTO user;
	
	private boolean output;
	
	private String message;
	
	public RegisterBean() {
		user = new UtenteDTO();
	}
	
	@PostConstruct
	public void init(){
	      FacesContext fc = FacesContext.getCurrentInstance();
	      Map<String,String> params = 
	      fc.getExternalContext().getRequestParameterMap();
	}
 
	public UtenteDTO getUser() {
		return user;
	}

	public void setUser(UtenteDTO user) {
		this.user = user;
	}
	
	public String register() {
		this.output = userMgr.save(user);
		if(output==true){
		this.message = "Registrazione effettuata con successo.";
		Thread t = new Thread(new Runnable() {
	         public void run()
	         {
	     		sendEmail(user.getEmail(),"Registrazione Travel Dream","Registrazione effettuata con successo!"
	     				+ "Per iniziare ad utilizzare il tuo nuovo account clicca sul seguente link: "
	     				+ "http://localhost:8080/TravelDreamOnlineWeb/valida.xhtml?email="+user.getEmail());
	         }
		});
		t.start();

		return "index?faces-redirect=true";
		}else{
		this.message = "L'email è stata già utilizzata per un altro account!";	
		return "";
		}
		
	}
	
	public void sendEmail(String to, String subject, String body) {

		MimeMessage message = new MimeMessage(mailSession);
		try {
		message.setFrom(new InternetAddress(mailSession.getProperty("mail.from")));
		InternetAddress[] address = {new InternetAddress(to)};
		message.setRecipients(MimeMessage.RecipientType.TO, address);
		message.setSubject(subject);
		message.setSentDate(new Date());
		message.setText(body);
		Transport.send(message);
		} catch (MessagingException ex) {
		ex.printStackTrace();
		}
		}

	public String getUserb() {
		return userb;
	}

	public void setUserb(String userb) {
		this.userb = userb;
	}

	public String red(){
		return "user/index?faces-redirect=true";
	}

	public boolean isOutput() {
		return output;
	}

	public void setOutput(boolean output) {
		this.output = output;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	
}
